package com.msy.rabbit.demo.controller;

import com.msy.rabbit.demo.dao.OrderRepository;
import com.msy.rabbit.demo.pojo.Order;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MessageController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    private OrderRepository repository;

    @GetMapping("/rabbit/{message}")
    public Order receive(@PathVariable String message) throws UnsupportedEncodingException {

        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding("utf-8")
                .setHeader("hello", "world")
                .build();
        Order order = new Order("1");
        Order save = repository.save(order);
        System.out.println(save);

        final Message msg = MessageBuilder
                .withBody(save.toString().getBytes("utf-8"))
                .andProperties(messageProperties)
                .build();

        rabbitTemplate.convertAndSend("ex.biz", "key.biz", save);

        return save;
    }


    @GetMapping("/listAll")
    public Map<String, Object> listAll() {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        //返回所有待付款订单
        Order order = new Order("1");
        objectObjectHashMap.put("code", 0);
        objectObjectHashMap.put("data", repository.findByState("1"));
        return objectObjectHashMap;
    }

    @GetMapping("/pay")
    public Map<String, Object> pay(Order order) {
        Map<String, Object> map = new HashMap<>();
        //判断是否是未付款状态
        Order order1 = repository.findById(order.getId()).get();
        if ("1".equals(order1.getState())) {
            order.setState("2");//付款成功
            repository.save(order);
            map.put("msg", "付款成功");
            map.put("code", 2);
        } else if ("3".equals(order1.getState())) {
            map.put("msg", "订单超时");
            map.put("code", 3);
        } else {
            map.put("msg", "已付款");
            map.put("code", 0);
        }
        return map;
    }

    @GetMapping("/timeout")
    public Map<String, Object> timeoutOrder() {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        //返回所有待付款订单
        objectObjectHashMap.put("code", 0);
        objectObjectHashMap.put("data", repository.findByState("3"));
        return objectObjectHashMap;
    }


}
